package com.cn.ccp.webservice.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.cn.ccp.bean.FacultyBean;
import com.cn.ccp.bean.GradeBean;
import com.cn.ccp.bean.ResourseBean;
import com.cn.ccp.bean.SpecialtyBean;
import com.cn.ccp.bean.TeachingGroupBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.service.faculty.FacultyService;
import com.cn.ccp.service.faculty.GradeService;
import com.cn.ccp.service.faculty.SpecialtyService;
import com.cn.ccp.service.faculty.TeachingGroupService;
import com.cn.ccp.service.resourse.ResourseService;
import com.cn.ccp.service.system.StudentService;
import com.cn.ccp.service.system.TeacherService;
import com.cn.ccp.service.system.UserService;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;
import com.cn.ccp.webservice.IWeb;
import com.cn.ccp.webservice.impl.SessionManager;
import com.cn.ccp.webservice.impl.UserSession;

public class WebImpl implements IWeb {

	private Logger log = Logger.getLogger(WebImpl.class);
	
	@Autowired
	private UserService userService;//用户查询service
	@Autowired
	private FacultyService facultyService;
	@Autowired
	private SpecialtyService specialtyService;
	@Autowired
	private TeachingGroupService teachingGroupService;
	@Autowired
	private GradeService gradeService;
	@Autowired
	private ResourseService resourseService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private StudentService studentService;
	
	private static SessionManager manager ; 
	public WebImpl(){
		manager = SessionManager.getManager();
	}
	
	@Override
	public String login(String userLoginName, String password) {
		log.info("---------------userLoginName = "+userLoginName);
		log.info("---------------password = "+password);
		boolean flag = userService.userNameExsit(userLoginName);
		log.info("---------------flag = "+flag);
		if(!flag)
			flag = userService.checkLoginNameIsOk(userLoginName);
		log.info("---------------flag = "+flag);
		StringBuffer buf = new StringBuffer();
		if(!flag){//用户名不存在
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		Object obj = userService.loginForWebservice(userLoginName,password);
		if(obj == null){//查询数据失败，没有响应的用户
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		UserBean u = (UserBean)obj;
		if(u.getStatus() == -1){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		log.info("login success and return value to client..");
		buf.append("{\"msg\":\"success\",\"student\":{");
		buf.append("\"id\":\""+u.getId()+"\",");
		buf.append("\"userName\":\""+u.getUserName()+"\", ");
		buf.append("\"number\":\""+u.getNumber()+"\",\"dormitoryAddress\":\""+u.getDormitoryAddress()+"\",\"email\":\""+u.getEmail()+"\",\"sex\":\""+u.getSex()+"\",\"faculty\":\""+u.getFaculty()+"\",\"specialtyName\":\""+u.getSpecialtyName()+"\",");
		if( u.getImage() != null  && isImage(u.getImage().trim())){
			String ext = u.getImage().split("\\.")[1];
			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+u.getId() + File.separator +"head-image."+ext);
			if(des.exists()){
				buf.append("\"image\":\""+"tempfile"+File.separator+u.getId() + File.separator +"head-image."+ext+"\",");
			}else
				buf.append("\"image\":\"\",");
		}else
			buf.append("\"image\":\""+u.getImage()+"\",");
		buf.append("\"gradeName\":\""+u.getGradeName()+"\"");
		buf.append("}}");
		
		UserSession session = manager.createUserSession(u); 
		manager.add(session);
//		log.info(session);
		
		log.info(buf.toString());
		return buf.toString();
	}

	@Override
	public void logout(int userId) {
		log.info(userId);
		manager.getUserSession(String.valueOf(userId)).setUnValid();
	}

	/**
	 * 查询所有学院信息
	 * @param userId：登录用户id
	 * @return
	 */
	public String queryFaculty(int userId){
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			List<FacultyBean> list = facultyService.getAllFaculty();
			ReturnValue value = new ReturnValue();
			List<FacultyObj> jsonList = new ArrayList<FacultyObj>();
			for(FacultyBean b : list )
				jsonList.add(new FacultyObj(b));
			value.setContents(jsonList);
			buf.append(JSONObject.fromObject(value).toString());
		}catch(Exception e){
			log.error("add faculty failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf.toString());
		return buf.toString();
	}
	
	@Override
	public String addFaculty(String facultyName, String description, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------facultyName = "+facultyName);
		if(facultyName == null || "".equalsIgnoreCase(facultyName)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para facultyName is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			FacultyBean facultyBean = new FacultyBean();
			facultyBean.setFacultyName(facultyName);
			facultyBean.setDescription(description);
			facultyService.saveFaculty(facultyBean);
			List<FacultyBean> list = facultyService.getAllFaculty();
			ReturnValue value = new ReturnValue();
			List<FacultyObj> jsonList = new ArrayList<FacultyObj>();
			for(FacultyBean b : list )
				jsonList.add(new FacultyObj(b));
			value.setContents(jsonList);
			buf.append(JSONObject.fromObject(value).toString());
		}catch(Exception e){
			log.error("add faculty failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf.toString());
		return buf.toString();
	}

	@Override
	public String updateFaculty(int id, String facultyName, String description,
			int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		log.info("---------------facultyName = "+facultyName);
		if(facultyName == null || "".equalsIgnoreCase(facultyName)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para facultyName is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			FacultyBean facultyBean = new FacultyBean();
			facultyBean.setId(id);
			facultyBean.setFacultyName(facultyName);
			facultyBean.setDescription(description);
			facultyService.updateFaculty(facultyBean);
			List<FacultyBean> list = facultyService.getAllFaculty();
			ReturnValue value = new ReturnValue();
			List<FacultyObj> jsonList = new ArrayList<FacultyObj>();
			for(FacultyBean b : list )
				jsonList.add(new FacultyObj(b));
			value.setContents(jsonList);
			buf.append(JSONObject.fromObject(value).toString());
		}catch(Exception e){
			log.error("update faculty  failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String deleteFaculty(int id, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			facultyService.deleteFaculty(id);
			List<FacultyBean> list = facultyService.getAllFaculty();
			ReturnValue value = new ReturnValue();
			List<FacultyObj> jsonList = new ArrayList<FacultyObj>();
			for(FacultyBean b : list )
				jsonList.add(new FacultyObj(b));
			value.setContents(jsonList);
			buf.append(JSONObject.fromObject(value).toString());
		}catch(Exception e){
			log.error("delete faculty  failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	private String querySpecialty(){
		List list = specialtyService.queryAll();
		ReturnValue value = new ReturnValue();
		List<SpecialtyObj> jsonList = new ArrayList<SpecialtyObj>();
		for(int i=0,n=list.size();i<n;i++  )
			jsonList.add(new SpecialtyObj((SpecialtyBean)list.get(i)));
		value.setContents(jsonList);
		return JSONObject.fromObject(value).toString();
	}
	
	/**
	 * 
	 * @param userId
	 * @return
	 */
	public String querySpecialty(int userId){
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			buf.append(querySpecialty());
		}catch(Exception e){
			log.error("query specialty  failed", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
		}
		log.info(buf.toString());
		return buf.toString();
	}
	
	@Override
	public String addSpecialty(String name, String des, int facultyId,
			int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------name = "+name);
		if(name == null || "".equalsIgnoreCase(name)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para name is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		log.info("---------------id = "+facultyId);
		if(facultyId < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		boolean flag = specialtyService.specialtyNameIsAlready(0, name,String.valueOf(facultyId));
		if(flag){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info("The specialty has been, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			SpecialtyBean b = new SpecialtyBean();
			b.setSpecialtyname(name);
			b.setDescription(des);
			b.setFacultyId(String.valueOf(facultyId));
			specialtyService.saveSpecialty(b);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("add specialty failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"5\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String updateSpecialty(int id, String name, String des,
			int facultyId, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------name = "+name);
		if(name == null || "".equalsIgnoreCase(name)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para name is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		log.info("---------------facultyId = "+facultyId);
		if(facultyId < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		boolean flag = specialtyService.specialtyNameIsAlready(id, name,String.valueOf(facultyId));
		if(flag){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"5\"}");
			log.info("The specialty has been, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			SpecialtyBean b = new SpecialtyBean();
			b.setId(id);
			b.setSpecialtyname(name);
			b.setDescription(des);
			b.setFacultyId(String.valueOf(facultyId));
			flag = specialtyService.updateSpecialty(b);
			log.info("---------------------------------flag = "+flag);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("update specialty failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"6\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String deleteSpecialty(int id, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			specialtyService.delSpecialty(id);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("delete specialty failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"6\"}");
		}
		log.info(buf);
		return buf.toString();
				
	}

	public String queryTeachingGroup(int userId){
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			List list = teachingGroupService.getTeachingGroupList(0, 10000);
			ReturnValue value = new ReturnValue();
			List<TeachingGroupObj> jsonList = new ArrayList<TeachingGroupObj>();
			for(int i=0,n=list.size();i<n;i++  )
				jsonList.add(new TeachingGroupObj((TeachingGroupBean)list.get(i)));
			value.setContents(jsonList);
			buf.append(JSONObject.fromObject(value).toString());
		}catch(Exception e){
			log.error("query teaching group failed  : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	
	@Override
	public String addTeachingGroup(String name, String des, int facultyId,
			int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------name = "+name);
		if(name == null || "".equalsIgnoreCase(name)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para name is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		log.info("---------------id = "+facultyId);
		if(facultyId < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			TeachingGroupBean b = new TeachingGroupBean();
			b.setTeaching_group_name(name);
			b.setTeaching_group_des(des);
			b.setFaculity_id(String.valueOf(facultyId));
			teachingGroupService.insert(b);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("add teaching group failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String updateTeachingGroup(int id, String name, String des,
			int facultyId, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		log.info("---------------name = "+name);
		if(name == null || "".equalsIgnoreCase(name)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para name is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
	
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			TeachingGroupBean b = new TeachingGroupBean();
			b.setId(id);
			b.setTeaching_group_name(name);
			b.setTeaching_group_des(des);
			b.setFaculity_id(String.valueOf(facultyId));
			teachingGroupService.update(b);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("update teaching group failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String deleteTeachingGroup(int id, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			teachingGroupService.delete(id);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("delete teaching group failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	public String queryGrade(int userId){
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			List list = gradeService.getAllGrade();
			ReturnValue value = new ReturnValue();
			List<GradeObj> jsonList = new ArrayList<GradeObj>();
			for(int i=0,n=list.size();i<n;i++  )
				jsonList.add(new GradeObj((GradeBean)list.get(i)));
			value.setContents(jsonList);
			buf.append(JSONObject.fromObject(value).toString());
		}catch(Exception e){
			log.error("query grade failed  : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
		}
		log.info(buf);
		return buf.toString();
	}
	
	@Override
	public String addGrade(String gradeNumber, String des, int specityId,
			int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------gradeNumber = "+gradeNumber);
		if(gradeNumber == null || "".equalsIgnoreCase(gradeNumber)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para gradeNumber is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		log.info("---------------specityId = "+specityId);
		if(specityId < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para specityId is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
 
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			GradeBean b = new GradeBean();
			b.setGradeType(gradeNumber);
			b.setDescription(des);
			b.setSpecialtyId(String.valueOf(specityId));
			gradeService.saveGrade(b);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("add specialty failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String updateGrade(int id, String gradeNumber, String des,
			int specityId, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		
		log.info("---------------gradeNumber = "+gradeNumber);
		if(gradeNumber == null || "".equalsIgnoreCase(gradeNumber)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info("The para gradeNumber is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
 
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			GradeBean b = new GradeBean();
			b.setId(id);
			b.setGradeType(gradeNumber);
			b.setDescription(des);
			b.setSpecialtyId(String.valueOf(specityId));
			gradeService.updateGrade(b);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("update grade failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String deleteGrade(int id, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
 
		session.setLastAccessedTime(System.currentTimeMillis());
		try{
			gradeService.deleteGrade(id);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("delete grade failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String queryUserType(int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		try{
			session.setLastAccessedTime(System.currentTimeMillis());
			List<ResourseBean> list = resourseService.pageQueryResourse(Contants.DATA_DICTIONARY_TEACHER_TYPE);
			ReturnValue value = new ReturnValue();
			List<UserType> jsonList = new ArrayList<UserType>();
			for(ResourseBean b : list )
				jsonList.add(new UserType(b));
			jsonList.add(new UserType(1,"学生"));
			value.setContents(jsonList);
			buf.append(JSONObject.fromObject(value).toString());
		}catch(Exception e){
			log.error("query user type failed : ",e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String addUser(String param, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------param = "+param);
		if(param == null || "".equalsIgnoreCase(param)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para  is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		JSONObject json = JSONObject.fromObject(param);
		
		 SimpleDateFormat  df  =  new  SimpleDateFormat("yyyy-MM-dd");  
		 df.setLenient(false);
		UserBean u = new UserBean();
		try{
			if(null != json.getString("userName") && !"".equalsIgnoreCase(json.getString("userName"))){
				u.setUserName(json.getString("userName"));//用户姓名
				u.setLogin_name(json.getString("userName"));
			}
		}catch(Exception e){}
		try{
			if(null != json.getString("password") && !"".equalsIgnoreCase(json.getString("password")))
				u.setPassword(json.getString("password"));//用户密码
		}catch(Exception e){}
		 
		try{	
			if(null != json.getString("homeAddress") && !"".equalsIgnoreCase(json.getString("homeAddress")))
					u.setHomeAddress(json.getString("homeAddress"));//家庭地址
		}catch(Exception e){}
		try{	
			if(null != json.getString("dormitoryAddress") && !"".equalsIgnoreCase(json.getString("dormitoryAddress")))
				u.setDormitoryAddress(json.getString("dormitoryAddress"));//宿舍地址
		}catch(Exception e){}
		try{	
			if(null != json.getString("email") && !"".equalsIgnoreCase(json.getString("email")))
				u.setEmail(json.getString("email"));
		}catch(Exception e){}
		try{	
			if(null != json.getString("phone") && !"".equalsIgnoreCase(json.getString("phone")))
				u.setMobile(json.getString("phone"));//学生电话
		}catch(Exception e){}
		try{	
			if(null != json.getString("birthday") && !"".equalsIgnoreCase(json.getString("birthday"))){
				u.setBirtdate(json.getString("birthday"));//生日
				try {
					df.parse(u.getBirtdate());
				} catch (Exception e) {
					log.info("birthday para is error : ",e);
					buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
					log.info(buf.toString());
					return buf.toString();
				}
			}
		}catch(Exception e){}
		try{	
			if(null != json.getString("timeOfEnrollment") && !"".equalsIgnoreCase(json.getString("timeOfEnrollment"))){
				u.setAdmissionTime(json.getString("timeOfEnrollment"));//入学时间 
				try {
					df.parse(u.getAdmissionTime());
				} catch (Exception e) {
					log.info("birthday para is error : ",e);
					buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
					log.info(buf.toString());
					return buf.toString();
				}
			}
		}catch(Exception e){}
		try{	
			if(null != json.getString("zipCode") && !"".equalsIgnoreCase(json.getString("zipCode")))
				u.setZipCode(json.getString("zipCode"));//邮编
		}catch(Exception e){}
		try{	
			if(null != json.getString("facultyId") && !"".equalsIgnoreCase(json.getString("facultyId")))
				u.setFaculty(json.getString("facultyId"));//学院id
		}catch(Exception e){}
		try{	
			if(null != json.getString("specityId") && !"".equalsIgnoreCase(json.getString("specityId")))
				u.setSpecialtyId(json.getString("specityId"));//专业id
		}catch(Exception e){}
		try{	
			if(null != json.getString("gradeId") && !"".equalsIgnoreCase(json.getString("gradeId")))
				u.setGrade(json.getString("gradeId"));//班级id
		}catch(Exception e){}
		try{	
			if(null != json.getString("userTypeId") && !"".equalsIgnoreCase(json.getString("userTypeId")))
				u.setUserType(json.getString("userTypeId"));//用户类型id
		}catch(Exception e){}
		try{	
			log.info(u);
			if("1".equalsIgnoreCase(u.getUserType()))//学生
				studentService.sava(u);
			else{
				teacherService.sava(u, new ArrayList());
			}
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("add user info failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"5\"}");
			log.info(buf.toString());
		}
		log.info(buf);
		return buf.toString();
		
	}

	@Override
	public String updateUser(String param, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		if(param == null || "".equalsIgnoreCase(param)){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.error("The para param is null, please input the right param.");
			log.info(buf);
			return buf.toString();
		}
		Object obj = null;
		try{
			log.info(userId);
			obj = userService.findById(userId);
		}catch(Exception e){
			log.error("query user detail failed for["+userId+"] :", e);
		}
		
		if(obj == null){//查询数据失败，没有响应的用户
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info(buf.toString());
			return buf.toString();
		}
		UserBean u = (UserBean)obj;
		session.setLastAccessedTime(System.currentTimeMillis());
		log.info(param);
		JSONObject json = JSONObject.fromObject(param);
		
		 SimpleDateFormat  df  =  new  SimpleDateFormat("yyyy-MM-dd");  
		 df.setLenient(false);
			try{
				if(null != json.getString("userName") && !"".equalsIgnoreCase(json.getString("userName")))
					u.setUserName(json.getString("userName"));//用户姓名
			}catch(Exception e){}
			
//			if(null != json.getString("password") && !"".equalsIgnoreCase(json.getString("password")))
//				u.setPassword(json.getString("password"));//密码
			try{	
				if(null != json.getString("homeAddress") && !"".equalsIgnoreCase(json.getString("homeAddress")))
						u.setHomeAddress(json.getString("homeAddress"));//家庭地址
			}catch(Exception e){}
			try{	
				if(null != json.getString("dormitoryAddress") && !"".equalsIgnoreCase(json.getString("dormitoryAddress")))
					u.setDormitoryAddress(json.getString("dormitoryAddress"));//宿舍地址
			}catch(Exception e){}
			try{	
				if(null != json.getString("email") && !"".equalsIgnoreCase(json.getString("email")))
					u.setEmail(json.getString("email"));
			}catch(Exception e){}
			try{	
				if(null != json.getString("phone") && !"".equalsIgnoreCase(json.getString("phone")))
					u.setMobile(json.getString("phone"));//学生电话
			}catch(Exception e){}
			try{	
				if(null != json.getString("birthday") && !"".equalsIgnoreCase(json.getString("birthday"))){
					u.setBirtdate(json.getString("birthday"));//生日
					try {
						df.parse(u.getBirtdate());
					} catch (Exception e) {
						log.info("birthday para is error : ",e);
						buf.append("{\"msg\":\"falied\",\"failedmsg\":\"5\"}");
						log.info(buf.toString());
						return buf.toString();
					}
				}
			}catch(Exception e){}
			try{	
				if(null != json.getString("timeOfEnrollment") && !"".equalsIgnoreCase(json.getString("timeOfEnrollment"))){
					u.setAdmissionTime(json.getString("timeOfEnrollment"));//入学时间 
					try {
						df.parse(u.getAdmissionTime());
					} catch (Exception e) {
						log.info("birthday para is error : ",e);
						buf.append("{\"msg\":\"falied\",\"failedmsg\":\"6\"}");
						log.info(buf.toString());
						return buf.toString();
					}
				}
			}catch(Exception e){}
			try{	
				if(null != json.getString("zipCode") && !"".equalsIgnoreCase(json.getString("zipCode")))
					u.setZipCode(json.getString("zipCode"));//邮编
			}catch(Exception e){}
		try{	
			log.info(u);
			userService.update(u, false);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("update user info failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"4\"}");
			log.info(buf.toString());
		}
		log.info(buf);
		return buf.toString();
	}

	@Override
	public String deleteUser(int id, int userId) {
		UserSession session = manager.getUserSession(String.valueOf(userId));
		StringBuffer buf = new StringBuffer();
		if(session == null){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"1\"}");
			log.info("user ["+userId+"] has not login and please login first.");
			log.info(buf);
			return buf.toString();
		}
		log.info("---------------id = "+id);
		if(id < 0){
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"2\"}");
			log.info("The para id is less than zero, please input the right param.");
			log.info(buf);
			return buf.toString();
		} 
		try{
			studentService.delete(id);
			buf.append("{\"msg\":\"success\"}");
		}catch(Exception e){
			log.error("delete user info failed : ", e);
			buf.append("{\"msg\":\"falied\",\"failedmsg\":\"3\"}");
			log.info(buf.toString());
		}
		log.info(buf);
		return buf.toString();
	}

	
	/**
	 *  是图片
	 * @param path
	 * @return
	 */
	 private boolean isImage(String path){
		 path = path.toLowerCase();
		 if(path.endsWith(".png") || path.endsWith(".jpg"))
			 return true;
		 else
			 return false;
	 }

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public FacultyService getFacultyService() {
		return facultyService;
	}

	public void setFacultyService(FacultyService facultyService) {
		this.facultyService = facultyService;
	}

	public SpecialtyService getSpecialtyService() {
		return specialtyService;
	}

	public void setSpecialtyService(SpecialtyService specialtyService) {
		this.specialtyService = specialtyService;
	}

	public TeachingGroupService getTeachingGroupService() {
		return teachingGroupService;
	}

	public void setTeachingGroupService(TeachingGroupService teachingGroupService) {
		this.teachingGroupService = teachingGroupService;
	}

	public GradeService getGradeService() {
		return gradeService;
	}

	public void setGradeService(GradeService gradeService) {
		this.gradeService = gradeService;
	}

	public ResourseService getResourseService() {
		return resourseService;
	}

	public void setResourseService(ResourseService resourseService) {
		this.resourseService = resourseService;
	}
	 
}
